<template>
  <div class="student-component" v-loading="loading">
    <!-- 添加功能条 -->
    <div class="function-bar">
      <div class="left-section">
        <ButtonPermission code="student:batchAdd" mode="disable">
          <template #default="{ disabled }">
            <el-button 
              type="primary" 
              size="small" 
              :disabled="disabled"
              @click="!disabled && importStudent()" 
              icon="el-icon-upload2"
            >批量新增</el-button>
          </template>
        </ButtonPermission>
        <ButtonPermission code="student:batchUpdate" mode="disable">
          <template #default="{ disabled }">
            <el-button 
              type="primary" 
              size="small" 
              :disabled="disabled"
              @click="!disabled && updateStudent()" 
              icon="el-icon-refresh"
            >批量更新</el-button>
          </template>
        </ButtonPermission>
        <ButtonPermission code="student:resetPwd" mode="disable">
          <template #default="{ disabled }">
            <el-button 
              type="primary" 
              size="small" 
              :disabled="disabled"
              @click="!disabled && batchResetPwd()" 
              icon="el-icon-key"
            >重置密码</el-button>
          </template>
        </ButtonPermission>
        <ButtonPermission code="student:export" mode="disable">
          <template #default="{ disabled }">
            <el-dropdown :disabled="disabled" @command="handleExportCommand" trigger="click">
              <el-button type="primary" size="small" icon="el-icon-download" :disabled="disabled">
                导出<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <ButtonPermission code="student:exportList" mode="disable">
                    <template #default="{ disabled: exportListDisabled }">
                      <el-dropdown-item command="all-info" :disabled="exportListDisabled">导出列表</el-dropdown-item>
                    </template>
                  </ButtonPermission>
                  <ButtonPermission code="student:exportAccount" mode="disable">
                    <template #default="{ disabled: exportAccountDisabled }">
                      <el-dropdown-item command="stu-account" :disabled="exportAccountDisabled">导出账号</el-dropdown-item>
                    </template>
                  </ButtonPermission>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </ButtonPermission>
      </div>
      <div class="right-section">
        <el-input
          class="search-input"
          v-model="studentName"
          prefix-icon="el-icon-search"
          placeholder="请输入学生姓名/考号查询"
          @input="inputChange"
          @clear="handleClear"
          clearable
          size="small"
        ></el-input>
      </div>
    </div>
    
    <div class="student-layout">
      <!-- 左侧班级树形结构 -->
      <div class="class-tree-container">
        <div class="tree-header">
          <i class="el-icon-school"></i> 班级
          <span class="debug-toggle" @click="debugMode = !debugMode" title="切换调试模式">
            <!-- <i class="el-icon-warning-outline"></i> -->
          </span>
        </div>
        <el-tree
          v-if="treeData.length > 0"
          ref="classTree"
          :data="treeData"
          node-key="id"
          :props="defaultProps"
          :highlight-current="true"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
          default-expand-all
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span :class="{'node-selected': currentNode && currentNode.id === data.id}">
                {{ node.label }}
                <span v-if="data.count && data.count > 0" class="count-tag">({{ data.count }})</span>
              </span>
            </span>
          </template>
        </el-tree>
        <pre v-if="treeData.length > 0 && debugMode" class="debug-tree">{{ JSON.stringify(treeData, null, 2) }}</pre>
        <div v-if="treeData.length === 0 && !loading" class="empty-tree">
          <i class="el-icon-warning-outline"></i>
          <p>暂无班级数据</p>
        </div>
        <div v-if="treeData.length === 0 && loading" class="loading-tree">
          <i class="el-icon-loading"></i>
          <p>正在加载班级数据...</p>
        </div>
      </div>

      <!-- 右侧学生列表 -->
      <div class="student-list-container">
        <!-- 修改班级/年级标题和搜索区域，移除v-if条件使其始终显示 -->
        <div class="class-info-header">
          <div class="header-row">
            <div class="class-title">
              <h2>{{ currentNode ? getSelectedNodeTitle() : '学生列表' }}</h2>
              <span v-if="!showStudentView" class="subtitle">班级列表 ({{ filteredClassList.length }})</span>
            </div>
          </div>
        </div>
        
        <!-- 可滚动的内容区域，包含任课老师和学生管理部分 -->
        <div class="scrollable-content" v-loading="loading">
          <!-- 班级信息列表 - 当点击学校根节点或年级节点时显示 -->
          <div v-if="!showStudentView" class="class-list-section">
            <!-- 功能按钮区域 -->
            <div class="action-buttons">
              <ButtonPermission code="class:add" mode="disable">
                <template #default="{ disabled }">
                  <el-button 
                    type="primary" 
                    size="small" 
                    :disabled="disabled"
                    @click="!disabled && addClass()" 
                    icon="el-icon-plus"
                  >新增班级</el-button>
                </template>
              </ButtonPermission>
            </div>
            
            <div class="table-wrapper">
              <el-table
                :data="filteredClassList"
                border
                stripe
                style="width: 100%"
                v-loading="loading"
                empty-text="暂无班级数据"
                header-cell-class-name="table-header"
                :max-height="tableMaxHeight"
              >
                <el-table-column prop="sort" label="序号" width="80" align="center"></el-table-column>
                <el-table-column label="班级名称" prop="F_class_name" align="center" min-width="150">
                  <template #default="scope">
                    {{ scope.row.F_class_name.includes(' - ') ? scope.row.F_class_name.split(' - ')[1] : scope.row.F_class_name }}
                  </template>
                </el-table-column>
                <el-table-column prop="student_count" label="学生人数" width="120" align="center">
                  <template #default="scope">
                    <span class="count-text">{{ scope.row.student_count || 0 }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="teacher_count" label="教师人数" width="120" align="center">
                  <template #default="scope">
                    <span class="count-text">{{ scope.row.teacher_count || 0 }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="240" align="center" fixed="right">
                  <template #default="scope">
                    <div class="action-buttons-cell">
                      <ButtonPermission code="class:viewStudents" mode="disable">
                        <template #default="{ disabled }">
                          <el-button 
                            type="text" 
                            size="small" 
                            class="view-btn"
                            :disabled="disabled"
                            @click="!disabled && viewClassStudents(scope.row)"
                          >查看学生</el-button>
                        </template>
                      </ButtonPermission>
                      <ButtonPermission code="class:edit" mode="disable">
                        <template #default="{ disabled }">
                          <el-button 
                            type="text" 
                            size="small" 
                            class="edit-btn"
                            :disabled="disabled"
                            @click="!disabled && editClass(scope.row)"
                          >编辑班级</el-button>
                        </template>
                      </ButtonPermission>
                      <ButtonPermission code="class:delete" mode="disable">
                        <template #default="{ disabled }">
                          <el-button 
                            type="text" 
                            size="small" 
                            class="delete-btn"
                            :disabled="disabled"
                            @click="!disabled && deleteClass(scope.$index, scope.row)"
                          >删除</el-button>
                        </template>
                      </ButtonPermission>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          
          <!-- 当选择的是班级时显示任课老师 -->
          <div v-if="currentNode && currentNode.classId && currentNode.classId !== 'unassigned' && showStudentView">
            <!-- 添加明确的任课老师标题 -->
            <div class="teacher-section-header">
              <div class="section-title">
                <i class="el-icon-user"></i>
                <span>任课老师</span>
              </div>
            </div>
            
            <div class="teacher-info" v-loading="teacherLoading">
              <div v-if="teacherLoading" style="text-align: center; padding: 20px;">
                <p>正在加载教师信息...</p>
              </div>
              <div v-else-if="!subjectTeachers.length && !classTeacherInfo.headTeacher" style="text-align: center; padding: 20px;">
                <p style="color: #909399;">暂无教师信息，点击"设置"按钮添加</p>
              </div>
              <div v-else class="teacher-info-row">
                <div class="teacher-item">
                  <span class="label">班主任</span>
                  <span class="value" @click="setSubjectTeacher(0)">{{ classTeacherInfo.headTeacher || '设置' }}</span>
                </div>
                
                <!-- 动态显示科目教师 -->
                <div class="teacher-item" v-for="subject in filteredSubjectTeachers" :key="subject.subjectId">
                  <span class="label">{{ subject.subjectName }}</span>
                  <span class="value" @click="setSubjectTeacher(subject.subjectId)">
                    {{ subject.teachers && subject.teachers.length > 0 
                        ? subject.teachers.map(t => t.name).join('/') 
                        : '设置' }}
                  </span>
                </div>
                
                <!-- 如果没有任何科目数据，显示默认科目 -->
                <template v-if="subjectTeachers.length <= 1">
                  <div class="teacher-item">
                    <span class="label">语文</span>
                    <span class="value" @click="setSubjectTeacher(1)">设置</span>
                  </div>
                  <div class="teacher-item">
                    <span class="label">数学</span>
                    <span class="value" @click="setSubjectTeacher(2)">设置</span>
                  </div>
                  <div class="teacher-item">
                    <span class="label">英语</span>
                    <span class="value" @click="setSubjectTeacher(3)">设置</span>
                  </div>
                  <div class="teacher-item">
                    <span class="label">物理</span>
                    <span class="value" @click="setSubjectTeacher(4)">设置</span>
                  </div>
                  <div class="teacher-item">
                    <span class="label">化学</span>
                    <span class="value" @click="setSubjectTeacher(5)">设置</span>
                  </div>
                  <div class="teacher-item">
                    <span class="label">生物</span>
                    <span class="value" @click="setSubjectTeacher(6)">设置</span>
                  </div>
                  <div class="teacher-item">
                    <span class="label">历史</span>
                    <span class="value" @click="setSubjectTeacher(7)">设置</span>
                  </div>
                  <div class="teacher-item">
                    <span class="label">政治</span>
                    <span class="value" @click="setSubjectTeacher(8)">设置</span>
                  </div>
                  <div class="teacher-item">
                    <span class="label">地理</span>
                    <span class="value" @click="setSubjectTeacher(9)">设置</span>
                  </div>
                </template>
              </div>
            </div>
          </div>
          
          <!-- 学生管理部分 -->
          <div class="student-section" v-if="showStudentView">
            <div class="section-header">
              <div class="section-title">
                <span class="icon-student"><i class="el-icon-user"></i></span>
                <span>学生信息 ({{ studentTotal }})</span>
              </div>
              
              <!-- 功能按钮区域 -->
              <div class="action-buttons">
                <ButtonPermission code="student:add" mode="disable">
                  <template #default="{ disabled }">
                    <el-button 
                      type="primary" 
                      size="small" 
                      :disabled="disabled"
                      @click="!disabled && toAddStudent()" 
                      icon="el-icon-plus"
                    >新增学生</el-button>
                  </template>
                </ButtonPermission>
                <ButtonPermission code="student:clear" mode="disable">
                  <template #default="{ disabled }">
                    <el-button 
                      type="danger" 
                      size="small" 
                      :disabled="disabled"
                      @click="!disabled && clearAllStudent()" 
                      icon="el-icon-delete"
                    >清空学生</el-button>
                  </template>
                </ButtonPermission>
                
                <!-- 列表设置按钮移到这里 -->
                <el-popover
                  placement="bottom"
                  width="120"
                  trigger="click"
                  @hide="updateColumnList"
                >
                  <template #reference>
                    <el-button type="info" size="small" icon="el-icon-setting"></el-button>
                  </template>
                  <div class="column-setting-popover-content">
                    <el-checkbox-group v-model="checkedList">
                      <el-checkbox
                        v-for="{ label, prop } in filterList"
                        :key="prop"
                        :label="prop"
                      >{{ label }}</el-checkbox>
                    </el-checkbox-group>
                  </div>
                </el-popover>
              </div>
            </div>
            

            <div class="table-wrapper">
              <el-table
                :data="studentList"
                border
                stripe
                height="auto"
                header-cell-class-name="table-header"
                v-if="showTable"
              >
                <el-table-column prop="F_name" label="姓名" align="center" width="120"></el-table-column>
                <el-table-column prop="F_no" label="学号/考号" align="center" width="120"></el-table-column>
                <el-table-column prop="F_account" label="学生账号" align="center" width="120"></el-table-column>
                <el-table-column prop="student_code" label="学籍号" align="center" width="120" v-if="checkedList.includes('student_code')"></el-table-column>
                <el-table-column prop="F_gender_name" label="性别" align="center" width="80"></el-table-column>
                <el-table-column prop="F_class_name" label="班级" align="center" width="120"></el-table-column>
                <el-table-column prop="identityNumber" label="身份证号" align="center" width="180" v-if="checkedList.includes('identityNumber')"></el-table-column>
                <el-table-column prop="F_phone" label="家长电话" align="center" width="120" v-if="checkedList.includes('F_phone')"></el-table-column>
                <el-table-column prop="is_default_passwd_str" label="密码已修改" align="center" width="100"></el-table-column>
                <el-table-column label="操作" align="center" fixed="right" min-width="120">
                  <template #default="scope">
                    <ButtonPermission code="student:edit" mode="disable">
                      <template #default="{ disabled }">
                        <el-button 
                          type="text" 
                          size="small" 
                          class="edit-btn" 
                          :disabled="disabled"
                          @click="!disabled && editStudent(scope.row)"
                        >编辑</el-button>
                      </template>
                    </ButtonPermission>
                    <ButtonPermission code="student:delete" mode="disable">
                      <template #default="{ disabled }">
                        <el-button 
                          type="text" 
                          size="small" 
                          :disabled="disabled"
                          @click="!disabled && deleteStudent(scope.$index, scope.row)"
                        >删除</el-button>
                      </template>
                    </ButtonPermission>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            
            <div class="footer">
              <el-pagination
                background
                layout="total, prev, pager, next"
                :total="studentTotal"
                v-model:current-page="page"
                @current-change="changePage"
              >
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <EditStudent
      ref="editStudent"
      v-if="showEditStudent"
      :student="student"
      :type="type"
      @update="updateEdit"
      @updateCombination="updateCombination"
    />
    <ResetPW
      v-if="showResetPassword"
      :isStudent="true"
      :gradeAndClass="gradeAndClass"
      @close="showResetPassword = false"
    />
    <SetTeacher
      v-if="showSetTeacher"
      :settingInfo="settingInfo"
      :gradeId="gradeId"
      @cancel="showSetTeacher = false"
      @update="setTeacherSuccess"
    />
    <EditClass
      v-if="showEditClass"
      :classId="currentClassItem.F_id"
      @update="updateClass"
      @cancel="showEditClass = false"
    />
    <AddClass
      v-if="showAddClass"
      @update="addNewClass"
      @cancel="showAddClass = false"
      :initGradeId="currentNode && currentNode.id.startsWith('grade_') ? currentNode.gradeId : 0"
      :classTotal="filteredClassList.length"
    />
  </div>
</template>

<script>
import { downloadExcelBlob, debounce } from '@/utils/utils';
import { STUDENT_COLUMN_LIST } from '@/utils/constant';
import { mapState, mapGetters, mapActions } from 'vuex';
import EditStudent from './editStudent';
import ResetPW from './ResetPW.vue';
import SetTeacher from './SetTeacher.vue';
import EditClass from './edit-class.vue';
import AddClass from './AddClass.vue';

export default {
  name: 'StudentComponent',
  components: {
    EditStudent,
    ResetPW,
    SetTeacher,
    EditClass,
    AddClass,
  },
  props: {
    updateMsg: {
      type: Number,
    },
  },
  data() {
    return {
      loading: false,
      gradeAndClass: {},
      gradeList: [],
      gradeId: 0,
      classList: [],
      classId: '',
      genderList: [],
      genderId: 0,
      page: 1,
      studentName: '',
      studentList: [],
      columnList: [],
      studentTotal: 0,
      student: {},
      showEditStudent: false,
      type: 1,
      showResetPassword: false,

      filterList: [
        { label: '学籍号', prop: 'student_code' },
        { label: '身份证号', prop: 'identityNumber' },
        { label: '家长电话', prop: 'F_phone' },
      ],
      checkedList: ['student_code'],
      showTable: true,
      
      // 新增的班级树形结构数据
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      currentNode: null,
      filterConfig: {
        studentId: true,
        identityId: false,
        parentInfo: false
      },
      debugMode: false,
      
      // 任课老师相关数据
      classTeacherInfo: {},
      teacherLoading: false,
      subjectTeachers: [],
      showSetTeacher: false,
      settingInfo: {},
      showStudentView: false, // 修改默认值为false，显示班级列表
      filteredClassList: [],
      
      // 班级编辑相关
      showEditClass: false,
      showAddClass: false,
      currentClassItem: {},
      
      // 表格最大高度
      tableMaxHeight: 'calc(100vh - 350px)'
    };
  },
  computed: {
    ...mapState('school', ['schoolOptions']),
    ...mapGetters('school', ['schoolId', 'schoolName', 'schoolSubjectList']),
    showExamSubjectList() {
      return this.studentList.some((e) => e.courseList.length);
    },
    filteredSubjectTeachers() {
      return this.subjectTeachers.filter(subject => subject.subjectId !== 0);
    }
  },
  watch: {
    // 监听父组件的批量导入成功的消息, 导入成功后刷新该子组件
    async updateMsg() {
      this.getNewData();
    },
    // 监听当前学校ID变化
    '$store.state.school.currentSchoolId': {
      handler(newVal, oldVal) {
        if (newVal) {
          if (newVal !== oldVal) {
            this.loading = true; // 设置加载状态
            this.getNewData();
          } else if (this.loading && !this.treeData.length) {
            // 如果处于加载状态且没有树形数据，重新获取数据
            this.getNewData();
          }
        }
      },
      immediate: true
    },
    gradeId() {
      this.page = 1;
      
      // 修改：确保当点击树形菜单时不重置班级ID
      // 通过检查 currentNode 是否存在并且具有年级和班级ID来判断是否是树形菜单点击导致的年级ID变化
      // 只有当不是从树形菜单点击或者只选中了年级节点时才重置班级ID
      const isTreeNodeClick = this.currentNode && this.currentNode.gradeId === this.gradeId && this.currentNode.classId;
      
      if (!isTreeNodeClick) {
        // 只有在非树形菜单点击的情况下才获取班级列表并重置班级ID
        this.getClassList();
      }
      
      this.getStudents();
      
      // 更新班级列表数据
      this.updateClassListData();
    },
    classId() {
      this.page = 1;
      this.getStudents();
    },
    genderId() {
      this.page = 1;
      this.getStudents();
    },
    studentName() {
      this._debouncedSearch();
    },
    page() {
      this.getStudents();
    },
    'filterConfig.studentId'() {
      this.updateCheckedList();
    },
    'filterConfig.identityId'() {
      this.updateCheckedList();
    },
    'filterConfig.parentInfo'() {
      this.updateCheckedList();
    },
    // 监听学校选项数据变化
    schoolOptions: {
      handler(newVal) {
        if (newVal && newVal.F_grades && Object.keys(newVal.F_grades).length > 0) {
          // 更新班级数据
          this.gradeAndClass = JSON.parse(JSON.stringify(newVal.F_grades || {}));
          // 更新下拉选项
          this.getGradeList();
          this.getClassList();
          // 重建树形结构
          this.buildTreeData();
          
          // 如果当前还没有数据，更新班级列表
          if (this.filteredClassList.length === 0 && !this.showStudentView) {
            this.updateClassListData();
            this.fetchClassDataInfo();
          }
        } else {
          console.warn('学校选项数据变化但数据无效');
        }
      },
      deep: true,
      immediate: false
    }
  },
  async created() {
    this.loading = true; // 设置初始加载状态
    this.genderList = [
      { id: 0, name: '全部性别' },
      { id: 1, name: '男' },
      { id: 2, name: '女' },
    ];
    
    // 初始化防抖函数（放在前面，确保总是被创建）
    this._debouncedSearch = debounce(() => {
      this.page = 1;
      this.getStudents();
    }, 500);
    
    // 添加事件总线监听器
    this.$bus.$on('open-student-import-dialog', this.importStudent);
    this.$bus.$on('open-student-export-dialog', this.exportStudentAllInfo);
    
    // 延迟初始化，确保父组件数据已加载
    await this.$nextTick();
    await this.initData();
  },
  beforeUnmount() {
    // 在组件销毁前移除事件监听，避免内存泄漏
    this.$bus.$off('open-student-import-dialog', this.importStudent);
    this.$bus.$off('open-student-export-dialog', this.exportStudentAllInfo);
    
    // 清理防抖函数
    if (this._debouncedSearch && this._debouncedSearch.cancel) {
      this._debouncedSearch.cancel();
    }
  },
  mounted() {
    // 如果数据还没加载，再次尝试初始化
    this.$nextTick(() => {
      if (this.treeData.length === 0 && (this.schoolId || this.$store.state.school.currentSchoolId)) {
        this.initData();
      }
    });
  },
  methods: {
    ...mapActions('school', ['GET_SCHOOL_OPTIONS']),
    
    // 数据初始化方法
    async initData() {
      try {
        // 首先确保有schoolId，如果没有则尝试从store获取currentSchoolId
        const currentSchoolId = this.schoolId || this.$store.state.school.currentSchoolId;
        
        if (!currentSchoolId) {
          console.warn('无可用学校ID，等待学校选择后再初始化数据');
          // 设置初始状态并返回
          this.treeData = [];
          this.currentNode = { 
            id: 'school_root',
            label: this.schoolName || '本校',
            gradeId: 0,
            classId: '' 
          };
          // 默认显示班级列表视图
          this.showStudentView = false;
          this.loading = false;
          return;
        }
        
        // 等待一下，确保父组件（ViewSchool）的数据已加载
        await new Promise(resolve => setTimeout(resolve, 100));
        
        // 获取学校选项数据 - 如果数据不存在或为空，则获取
        const hasValidData = this.schoolOptions && 
                            this.schoolOptions.F_grades && 
                            Object.keys(this.schoolOptions.F_grades).length > 0;
        
        if (!hasValidData) {
          try {
            await this.GET_SCHOOL_OPTIONS({
              school_id: currentSchoolId
            });
          } catch (error) {
            console.error('获取学校选项数据失败:', error);
            this.loading = false;
            return;
          }
        }
        
        // 再次检查数据是否有效
        if (!this.schoolOptions || !this.schoolOptions.F_grades || Object.keys(this.schoolOptions.F_grades || {}).length === 0) {
          console.warn('学校选项数据无效，延迟重试...');
          // 延迟重试
          setTimeout(() => {
            this.initData();
          }, 500);
          return;
        }
        
        // 更新班级数据
        this.gradeAndClass = JSON.parse(
          JSON.stringify(this.schoolOptions?.F_grades || {})
        );
        
        // 初始化下拉选项
        this.getGradeList();
        this.getClassList();
        
        // 构建树形结构
        this.buildTreeData();
        
        // 设置初始节点为学校根节点
        this.currentNode = { 
          id: 'school_root',
          label: this.schoolName || '本校',
          gradeId: 0,
          classId: '' 
        };
        
        // 默认显示班级列表视图
        this.showStudentView = false;
        
        // 更新班级列表数据
        this.updateClassListData();
        
        // 获取真实班级数据
        await this.fetchClassDataInfo();
        
        // 手动触发一次handleNodeClick，确保数据加载
        await this.$nextTick();
        if (this.currentNode) {
          this.handleNodeClick(this.currentNode);
        }
      } catch (error) {
        console.error('组件初始化过程中发生错误:', error);
        // 不再使用静态树形数据
        this.treeData = [];
        this.getStudents();
      } finally {
        this.loading = false;
      }
    },
    
    // 构建树形数据结构
    buildTreeData() {
      let treeData = [];
      
      try {
        // 如果schoolOptions为空或无F_grades属性，返回空数组
        if (!this.schoolOptions || !this.schoolOptions.F_grades) {
          return [];
        }
        
        const gradeAndClass = JSON.parse(
          JSON.stringify(this.schoolOptions.F_grades || {})
        );
        
        // 如果年级数据为空对象，返回空数组
        if (Object.keys(gradeAndClass).length === 0) {
          return [];
        }
        
        // 创建本校根节点
        const rootNode = {
          id: 'school_root',
          label: this.schoolName || '本校',
          count: 0, // 将在遍历班级时更新
          gradeId: 0,
          classId: '',
          children: []
        };
        
        // 遍历年级数据，构建树形结构
        for (const gradeId in gradeAndClass) {
          const classes = gradeAndClass[gradeId] || [];
          
          // 获取年级信息
          const gradeInfo = this.$maps.gradeList.find(g => g.id === Number(gradeId));
          
          if (gradeInfo) {
            
            // 创建年级节点
            const gradeNode = {
              id: `grade_${gradeId}`,
              label: gradeInfo.name,
              count: classes.length > 0 ? classes.reduce((total, cls) => total + (cls.student_count || 0), 0) : 0,
              gradeId: Number(gradeId),
              classId: '',
              children: []
            };
            
            // 添加班级节点
            classes.forEach(classInfo => {
              gradeNode.children.push({
                id: `${gradeId}_${classInfo.F_class_id}`,
                label: classInfo.F_class_name,
                gradeId: Number(gradeId),
                classId: classInfo.F_class_id,
                count: classInfo.student_count || 0
              });
            });
            
            // 更新根节点的学生数量
            rootNode.count += gradeNode.count;
            
            // 添加到根节点的子节点
            rootNode.children.push(gradeNode);
          } else {
            console.warn(`无法找到年级信息: ${gradeId}`);
          }
        }
        
        // 将根节点添加到树形数据
        treeData.push(rootNode);
        
        this.treeData = treeData;
        return treeData;
      } catch (error) {
        console.error('构建树形结构出错:', error);
        return [];
      }
    },
    
    // 树节点点击处理
    handleNodeClick(data) {
      this.currentNode = data;
      
      // 提取节点数据
      let gradeId = 0;
      let classId = '';
      
      // 处理节点类型
      if (data.id === 'school_root') {
        // 点击学校根节点，显示所有班级信息
        gradeId = 0;
        classId = '';
        // 当点击学校根节点时，重置教师信息
        this.subjectTeachers = [];
        this.classTeacherInfo = {};
        // 切换到班级列表视图
        this.showStudentView = false;
      } else if (data.id.startsWith('grade_')) {
        // 点击年级节点，显示该年级所有班级信息
        gradeId = data.gradeId || 0;
        classId = '';
        // 当点击年级节点时，重置教师信息
        this.subjectTeachers = [];
        this.classTeacherInfo = {};
        // 切换到班级列表视图
        this.showStudentView = false;
      } else {
        // 点击班级节点，显示该班级的学生信息
        gradeId = data.gradeId || 0;
        classId = data.classId || '';
        
        // 如果classId是'unassigned'，则设置为空字符串
        if (classId === 'unassigned') {
          classId = '';
        }
        // 切换到学生列表视图
        this.showStudentView = true;
      }
      
      // 设置筛选条件
      this.gradeId = gradeId;
      this.classId = String(classId);
      
      console.log('设置筛选条件: 年级=', gradeId, '班级=', this.classId);
      
      // 重置页码并获取数据
      this.page = 1;
      
      if (this.showStudentView) {
        // 学生视图，获取学生数据
        this.getStudents();
        
        // 如果选中的是班级节点，获取班级的教师信息
        if (classId && classId !== '' && classId !== 'unassigned') {
          // 推迟获取教师信息，确保不与其他请求冲突
          this.$nextTick(() => {
            setTimeout(() => {
              this.getClassTeacherInfo(classId);
            }, 500);
          });
        }
      } else {
        // 班级列表视图，更新班级列表数据
        this.updateClassListData();
        
        // 获取真实班级数据
        this.$nextTick(() => {
          this.fetchClassDataInfo();
        });
      }
    },
    
    // 更新过滤列表
    updateCheckedList() {
      // 直接根据设置来调整checkedList，不再经过filterConfig
      // 保留原有逻辑，仅修改实现方式
      this.checkedList = [];
      
      // 添加默认选中的列
      this.checkedList.push('student_code'); // 默认显示学籍号
      
      // 根据项目需求可添加其他默认列
      
      // 更新列表
      this.getColumnList();
    },
    
    getExamSubjectText(list) {
      if (!list.length) return '';
      const array = this.schoolSubjectList
        .filter((e) => list.includes(e.id))
        .map((e) => e.name);
      return ['语文', '数学', ...array].join('、');
    },
    batchResetPwd() {
      this.showResetPassword = true;
    },
    async getNewData() {
      console.log('开始获取新数据');
      this.loading = true;
      
      try {
        // 获取当前使用的学校ID
        const currentSchoolId = this.schoolId || this.$store.state.school.currentSchoolId;
        
        if (!currentSchoolId) {
          console.error('无法获取学校ID，无法加载数据');
          this.loading = false;
          return;
        }
        
        // 重新获取学校选项数据
        await this.GET_SCHOOL_OPTIONS({
          school_id: currentSchoolId
        });
        
        // 更新班级数据
        this.gradeAndClass = JSON.parse(
          JSON.stringify(this.schoolOptions?.F_grades || {})
        );
        
        // 更新下拉选项
        this.getGradeList();
        this.getClassList();
        
        // 构建树形结构
        this.buildTreeData();
        
        // 获取学生数据
        await this.getStudents();
      } catch (error) {
        console.error('获取新数据失败:', error);
        // 出错时不显示任何数据
        this.treeData = [];
        await this.getStudents();
      } finally {
        this.loading = false;
      }
    },
    async clearAllStudent() {
      this.$EleMessageBox
        .confirm('是否确认清空所有学生？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(async () => {
          this.loading = true;
          try {
            const { F_responseNo, F_responseMsg } =
              await this.$api.clearStudents({
                F_school_id: this.schoolId,
                F_grade: this.gradeId,
                F_class_id: this.classId,
                F_gender: this.genderId,
                F_name: this.studentName,
              });
            if (F_responseNo === 10000) {
              
              this.$message.success('清空学生成功');
              await this.getStudents();
            } else {
              this.$message.error(`清空学生失败:${F_responseMsg}`);
             
            }
            this.loading = false;
          } catch (e) {
            this.loading = false;
            console.error(e);
            this.$message.error(`清空学生失败:${F_responseMsg}`);
          }
        })
        .catch(() => {});
    },
    importStudent() {
      this.$import(this.schoolId, this.$maps.importType.STUDENT, async () => {

        this.$message.success('批量导入学生数据成功');
        await this.GET_SCHOOL_OPTIONS({
          school_id: this.schoolId,
        });
        this.gradeAndClass = JSON.parse(
          JSON.stringify(this.schoolOptions.F_grades || {})
        );
        this.getGradeList();
      });
    },
    updateStudent() {
      this.$import(
        this.schoolId,
        this.$maps.importType.UPDATE_STUDENT,
        async () => {
          this.$message.success('批量更新学生数据成功');
          await this.GET_SCHOOL_OPTIONS({
            school_id: this.schoolId,
          });
          this.gradeAndClass = JSON.parse(
            JSON.stringify(this.schoolOptions.F_grades || {})
          );
          this.getGradeList();
        }
      );
    },
    async exportStudentAllInfo() {
      this.loading = true;
      try {
        const res = await this.$api.exportSchoolStudent({
          F_school_id: this.schoolId,
          F_grade: this.gradeId,
          F_class_id: this.classId,
          F_gender: this.genderId,
          F_name: this.studentName,
        });
        console.log(res);
        downloadExcelBlob(res, `${this.schoolName}学生信息`);
      } catch (e) {
        console.error(e);
        this.$message.error('导出学生信息失败,请联系后台管理员');

      }
      this.loading = false;
    },
    async exportStudentAccount() {
      this.loading = true;
      try {
        const res = await this.$api.exportStudentAccount({
          F_grade: this.gradeId,
          F_class_id: this.classId,
          F_gender: this.genderId,
          F_name: this.studentName,
          F_school_id: this.schoolId,
        });
        downloadExcelBlob(res, `${this.schoolName}-学生账号`);
        this.$message.success('导出学生账号成功');
      } catch (e) {
        console.error(e);
        this.$message.error('导出失败，请联系后台成员');
      }
      this.loading = false;
    },
    toSearch() {
      this.page = 1;
      this.getStudents();
    },
    async getStudents() {
      // 获取当前使用的学校ID
      const currentSchoolId = this.schoolId || this.$store.state.school.currentSchoolId;
      
      // 如果没有学校ID，不进行API调用
      if (!currentSchoolId) {
        this.loading = false;
        this.studentList = [];
        this.studentTotal = 0;
        return;
      }
      
      this.loading = true;
      
      const params = {
        F_grade: this.gradeId,
        F_class_id: this.classId,
        F_gender: this.genderId,
        F_name: this.studentName,
        F_page: this.page,
        F_limit: 10,
        F_school_id: currentSchoolId,
      };
      
      // 确保班级ID格式正确
      if (params.F_class_id === 'unassigned') {
        params.F_class_id = '';
      }
      
      try {
        const res = await this.$api.getStudents(params);
        // 确保 F_total 有默认值，如果未定义则使用学生列表长度
        this.studentTotal = res.F_total ?? (res.F_students?.length || 0);
        this.handleStuList(res.F_students || []);
      } catch (error) {
        console.error('获取学生数据失败:', error);
        // 发生错误时重置总数和学生列表
        this.studentTotal = 0;
        this.studentList = [];
      } finally {
        this.loading = false;
      }
    },
    handleStuList(list) {
      list.sort((a, b) => Number(a.F_grade) - Number(b.F_grade));
      list.forEach((student) => {
        const { F_gender, is_default_passwd, F_grade, courseType, courses } = student;
        // 设置性别显示文本
        student.F_gender_name = F_gender === 1 ? '男' : F_gender === 2 ? '女' : '-';
        // 设置密码是否修改标识
        student.is_default_passwd_str = is_default_passwd ? '' : '是';
        
        // 处理选考科目数据
        try {
          // 解析courses JSON数据
          const parsedCourses = courses ? (courses === '' ? [] : JSON.parse(courses)) : [];
          // 存储原始课程ID列表
          student.courseList = Array.isArray(parsedCourses) ? parsedCourses : [];
          
          // 处理高中年级的选考科目显示
          if (Number(F_grade) >= 10 && courseType !== 0) {
            // 根据课程ID获取课程名称
            const selectedSubjects = this.schoolSubjectList.filter((subject) => 
              student.courseList.includes(subject.id)
            );
            
            // 设置课程显示文本
            if (selectedSubjects.length > 0) {
              student.course_str = ['语文', '数学'].concat(
                selectedSubjects.map(subject => subject.name)
              ).join('、');
            } else {
              student.course_str = '';
            }
          } else {
            student.course_str = '';
          }
        } catch (error) {
          console.error(`解析学生科目信息出错:`, error, student);
          student.courseList = [];
          student.course_str = '';
        }
      });

      this.studentList = list;
      this.getColumnList();
    },
    getColumnList() {
      const toFilterPropList = this.filterList
        .filter((e) => !this.checkedList.includes(e.prop))
        .map((e) => e.prop);

      if (this.studentList.every((e) => e.courseType === 0)) {
        toFilterPropList.push('course_str');
      }

      this.columnList = STUDENT_COLUMN_LIST.filter(
        (e) => !toFilterPropList.includes(e.prop)
      );

      this.showTable = false;
      this.$nextTick(() => {
        this.showTable = true;
      });
    },
    getGradeList() {
      this.gradeList = [];
      for (let gradeId in this.gradeAndClass) {
        const res = this.$maps.gradeList.find((e) => e.id === Number(gradeId));
        if (res) this.gradeList.push(res);
      }
      this.gradeList.unshift({ id: 0, name: '全部年级' });
    },
    getClassList(keepClassId = false) {
      this.classList = [];
      if (this.gradeId === 0) {
        this.classList = [{ F_class_id: '', F_class_name: '全部班级' }];
      } else {
        const list =
          JSON.parse(JSON.stringify(this.gradeAndClass[this.gradeId])) || [];
        list.unshift({ F_class_id: '', F_class_name: '全部班级' });
        this.classList = list;
      }
      
      // 只有当不需要保持班级ID时才重置
      if (!keepClassId) {
        this.classId = '';
      }
    },
    inputChange() {
      // 如果当前在班级列表视图（显示学校或年级下的班级列表），切换到学生列表视图
      if (!this.showStudentView) {
        this.showStudentView = true;
      }
      
      // 如果是在搜索框中输入关键词，则清除班级选择，搜索全校范围内的学生
      if (this.studentName) {
        this.classId = '';
      }
      
      this._debouncedSearch();
    },

    changePage(val) {
      this.page = val;
      this.getStudents();
    },
    handleCommand(command) {
      switch (command) {
        case 'add-student':
          this.toAddStudent();
          break;
        case 'import-student':
          this.importStudent();
          break;
        default:
          break;
      }
    },
    handleExportCommand(command) {
      switch (command) {
        case 'all-info':
          this.exportStudentAllInfo();
          break;
        case 'stu-account':
          this.exportStudentAccount();
          break;
        default:
          break;
      }
    },
    toAddStudent() {
      // 创建基础学生对象
      const newStudent = {
        F_name: '',
        F_gender: 1,
        F_phone: '',
        F_no: '', // 学号就是考号
        F_grade: '', // 该学生所在年级
        F_class_id: '', // 所在班级id
        F_class_name: '',
        F_account: '', // 学生账号
        courseList: [],
        identityNumber: '',
        lockClass: true, // 添加锁定班级标志，防止用户修改班级
      };
      
      // 如果当前有选中班级，自动填充班级信息
      if (this.currentNode && this.currentNode.classId && this.currentNode.classId !== 'unassigned') {
        // 填充班级ID和班级名称
        newStudent.F_class_id = this.currentNode.classId;
        newStudent.F_class_name = this.currentNode.label || '';
        
        // 填充年级信息
        if (this.currentNode.gradeId) {
          newStudent.F_grade = String(this.currentNode.gradeId);
        }
        
        console.log('自动填充班级信息:', {
          班级ID: newStudent.F_class_id,
          班级名称: newStudent.F_class_name,
          年级: newStudent.F_grade
        });
      } 
      // 如果通过筛选条件选择了班级，也自动填充
      else if (this.classId && this.classId !== '') {
        // 查找当前班级信息
        const classInfo = this.classList.find(cls => cls.F_class_id === this.classId);
        if (classInfo) {
          newStudent.F_class_id = this.classId;
          newStudent.F_class_name = classInfo.F_class_name;
          
          // 填充年级信息
          if (this.gradeId) {
            newStudent.F_grade = String(this.gradeId);
          }
          
          console.log('从筛选条件自动填充班级信息:', {
            班级ID: newStudent.F_class_id,
            班级名称: newStudent.F_class_name,
            年级: newStudent.F_grade
          });
        }
      }
      // 如果只选择了年级，填充年级信息
      else if (this.gradeId && this.gradeId !== 0) {
        newStudent.F_grade = String(this.gradeId);
        console.log('自动填充年级信息:', {
          年级: newStudent.F_grade
        });
        // 未选择班级时不锁定
        newStudent.lockClass = false;
      }
      else {
        // 未指定班级时，不锁定
        newStudent.lockClass = false;
      }
      
      this.type = this.$maps.type.ADD;
      this.student = newStudent;
      this.showEditStudent = true;
    },
    updateCombination() {
      this.getStudents();
    },
    editStudent(item) {
      this.type = this.$maps.type.EDIT;
      // 添加锁定班级标记为false，允许编辑班级
      item.lockClass = false;
      this.student = item;
      this.showEditStudent = true;
    },
    async updateEdit(val) {
      if (!val) {
        this.showEditStudent = false;
        return;
      }

      // 从编辑组件获取选考科目数据
      const editStudentRef = this.$refs['editStudent'];
      if (!editStudentRef) {
        this.$message.error('编辑组件引用获取失败，无法保存科目数据');
        return;
      }

      let { language, courseType, checkedSubject } = editStudentRef;
      
      // 如果从组件直接获取的选考数据为空，尝试从val中的courseList获取
      if (val.courseList && Array.isArray(val.courseList) && val.courseList.length > 0) {
        console.log('从学生数据中获取选考科目:', val.courseList);
        // 优先使用已经保存在学生对象中的科目列表
        const idList = val.courseList.filter(id => id !== 0);
        const courses = idList.length ? JSON.stringify(idList) : '';
        
        const studentInfo = {
          ...val,
          courses,
          F_school_id: this.schoolId,
        };
        
        // 删除courseList字段，避免提交给后端
        delete studentInfo.courseList;
        
        if (this.type === this.$maps.type.EDIT) {
          studentInfo.F_student_id = val.F_id;
        }
        
        const formData = new FormData();
        for (let i in studentInfo) {
          formData.append(i, studentInfo[i]);
        }
        
        let api = async () => {};
        let text = '';
        if (this.type === this.$maps.type.ADD) {
          text = '添加';
          api = this.$api.addStudent;
        } else {
          text = '修改';
          api = this.$api.updateStudent;
        }
        
        try {
          const { F_responseNo, F_responseMsg } = await api(formData);
          if (F_responseNo === 10000) {
            this.$message.success(`${text}成功`);
            this.showEditStudent = false;
            this.getStudents();
          } else {
            this.$message.error(`${text}失败: ${F_responseMsg}`);
          }
        } catch (e) {
          console.error(e);
          this.$message.error(`${text}失败, 请联系后台管理员`);   
        }
      } else {
        // 旧的方式：从组件直接获取选考科目数据
        console.log('从编辑组件中获取选考科目信息:', { language, courseType, checkedSubject });
        const idList = [language, courseType, ...checkedSubject].filter(
          (e) => e !== 0
        );
        const courses = idList.length ? JSON.stringify(idList) : '';
        const studentInfo = {
          ...val,
          courses,
          F_school_id: this.schoolId,
        };
        
        // 删除courseList字段，避免提交给后端
        delete studentInfo.courseList;
        
        if (this.type === this.$maps.type.EDIT) {
          studentInfo.F_student_id = val.F_id;
        }
        
        const formData = new FormData();
        for (let i in studentInfo) {
          formData.append(i, studentInfo[i]);
        }
        
        let api = async () => {};
        let text = '';
        if (this.type === this.$maps.type.ADD) {
          text = '添加';
          api = this.$api.addStudent;
        } else {
          text = '修改';
          api = this.$api.updateStudent;
        }
        
        try {
          const { F_responseNo, F_responseMsg } = await api(formData);
          if (F_responseNo === 10000) {
            this.$message.success(`${text}成功`);
            this.showEditStudent = false;
            this.getStudents();
          } else {
            this.$message.error(`${text}失败: ${F_responseMsg}`);
          }
        } catch (e) {
          console.error(e);
          this.$message.error(`${text}失败, 请联系后台管理员`);   
        }
      }
    },
    deleteStudent(index, item) {
      const { F_id, F_name } = item;
      this.$delete(F_name, async () => {
        try {
          const { F_responseNo, F_responseMsg } = await this.$api.deleteStudent(
            {
              F_school_id: this.schoolId,
              F_student_id: F_id,
            }
          );
          if (F_responseNo === 10000) {
            this.$message.success('删除学生成功');
            this.getStudents();
          } else this.$message.error(`删除学生失败:${F_responseMsg}`);
        } catch (e) {
          console.error(e);
          this.$message.error('删除学生失败');    
        }
      });
    },
    getSelectedNodeTitle() {
      if (!this.currentNode) return '学生列表';
      
      // 处理节点类型
      if (this.currentNode.id === 'school_root') {
        // 根据视图类型显示不同标题
        return this.showStudentView 
          ? (this.studentName ? `"${this.studentName}" 的搜索结果` : this.currentNode.label + ' - 学生列表')
          : this.currentNode.label + ' - 班级管理';
      } else if (this.currentNode.id.startsWith('grade_')) {
        // 根据视图类型显示不同标题
        return this.showStudentView 
          ? (this.studentName ? `"${this.studentName}" 的搜索结果` : this.currentNode.label + ' - 学生列表')
          : this.currentNode.label + ' - 班级管理';
      } else if (this.currentNode.classId && this.currentNode.classId !== 'unassigned') {
        // 显示班级名称 - 学生管理
        return this.studentName 
          ? `${this.currentNode.label} - "${this.studentName}" 的搜索结果` 
          : this.currentNode.label + ' - 学生管理';
      } 
      
      return '学生列表';
    },
    // 任课老师信息处理
    async getClassTeacherInfo(classId) {
      if (!classId || classId === 'unassigned') {
        this.subjectTeachers = [];
        this.classTeacherInfo = {};
        return;
      }
      
      this.teacherLoading = true;
      console.log('开始获取班级教师信息, classId:', classId, 'schoolId:', this.schoolId, 'gradeId:', this.gradeId);
      
      try {
        // 修改为与TeachInfoView.vue完全相同的API调用方式
        // TeachInfoView中主要使用F_grade参数，而不是直接使用F_class_id
        const params = {
          F_school_id: this.schoolId,
          F_page: 1,
          F_limit: 100 // 获取足够多的数据以确保包含所有班级
        };
        
        // 必须确保有年级ID，这是获取教学信息的关键
        if (this.gradeId && this.gradeId !== 0) {
          params.F_grade = this.gradeId;
        } else {
          // 如果没有年级ID，尝试从classId中提取
          // 典型的classId格式可能是 "10_1"，其中10是年级ID，1是班级ID
          const parts = classId.toString().split('_');
          if (parts.length > 1) {
            params.F_grade = parseInt(parts[0], 10);
          } else {
            console.warn('无法确定年级ID，可能导致无法获取教师信息');
          }
        }
        
        console.log('获取班级教师信息请求参数:', params);
        const response = await this.$api.getTeachInfoList(params);
        console.log('获取班级教师信息响应:', response);
        
        const { F_data, F_responseNo, F_responseMsg } = response;
        
        if (F_responseNo === 10000 && F_data && F_data.class_infos && F_data.class_infos.length > 0) {
          // 找到对应班级的信息
          const allClassInfos = F_data.class_infos;
          console.log('获取到的所有班级教师信息:', allClassInfos);
          
          // 根据classId找到对应的班级信息
          const classInfo = allClassInfos.find(info => info.class_id.toString() === classId.toString());
          
          if (classInfo) {
            console.log('找到当前班级的教学信息:', classInfo);
            this.classTeacherInfo = classInfo;
            
            // 处理学科教师信息
            this.processSubjectTeachers(classInfo.subject_infos || []);
            
            console.log('处理后的学科教师信息:', this.subjectTeachers);
            console.log('班主任信息:', this.classTeacherInfo.headTeacher);
          } else {
            console.warn('在获取到的班级列表中未找到当前班级:', classId);
            console.warn('可用的班级ID列表:', allClassInfos.map(info => info.class_id));
            this.subjectTeachers = [];
            this.classTeacherInfo = {};
          }
        } else {
          console.warn('获取班级教师信息失败:', F_responseMsg, F_responseNo);
          console.warn('未找到班级信息，可能需要检查数据结构:', F_data);
          this.subjectTeachers = [];
          this.classTeacherInfo = {};
        }
      } catch (error) {
        console.error('获取班级教师信息出错:', error);
        this.subjectTeachers = [];
        this.classTeacherInfo = {};
      } finally {
        this.teacherLoading = false;
      }
    },

    // 处理学科教师信息
    processSubjectTeachers(subjectInfos) {
      console.log('处理学科教师信息, 原始数据:', subjectInfos);
      
      if (!subjectInfos || !Array.isArray(subjectInfos) || subjectInfos.length === 0) {
        console.warn('科目信息为空或格式不正确');
        this.subjectTeachers = [];
        return;
      }

      try {
        // 先找班主任（通常subject_id为0的是班主任）
        const headTeacher = subjectInfos.find(subject => subject.subject_id === 0);
        console.log('找到的班主任信息:', headTeacher);
        
        // 处理所有学科教师
        this.subjectTeachers = subjectInfos.map(subject => {
          // 确保subject_id存在
          if (subject.subject_id === undefined) {
            console.warn('科目数据缺少subject_id:', subject);
            return null;
          }
          
          // 创建规范化的教师数据对象
          const teacherData = {
            subjectId: subject.subject_id,
            subjectName: subject.subject_name || this.getSubjectNameById(subject.subject_id),
            teachers: []
          };
          
          // 确保teacher_infos存在且是数组
          if (subject.teacher_infos && Array.isArray(subject.teacher_infos)) {
            teacherData.teachers = subject.teacher_infos.map(teacher => {
              // 规范化教师数据
              const teacherInfo = {
                id: teacher.TeacherId || '',
                name: teacher.TeacherName || '未知教师',
                phone: teacher.Phone || ''
              };
              
              return teacherInfo;
            }).filter(t => t.id); // 过滤掉没有ID的教师
          } else {
            console.warn(`科目 ${teacherData.subjectName} 没有教师信息或格式不正确`);
          }
          
          console.log(`科目 ${teacherData.subjectName}(${teacherData.subjectId}) 教师:`, teacherData.teachers);
          return teacherData;
        }).filter(Boolean); // 过滤掉null值
        
        // 记录班主任信息
        if (headTeacher && headTeacher.teacher_infos && Array.isArray(headTeacher.teacher_infos) && headTeacher.teacher_infos.length > 0) {
          const headTeacherInfo = headTeacher.teacher_infos[0];
          if (headTeacherInfo && headTeacherInfo.TeacherName) {
            console.log('设置班主任:', headTeacherInfo.TeacherName);
            this.classTeacherInfo.headTeacher = headTeacherInfo.TeacherName;
          } else {
            console.warn('班主任数据格式不正确:', headTeacherInfo);
            this.classTeacherInfo.headTeacher = '';
          }
        } else {
          console.log('没有找到班主任信息');
          this.classTeacherInfo.headTeacher = '';
        }
        
        console.log('处理完成后的科目教师列表:', this.subjectTeachers);
      } catch (error) {
        console.error('处理学科教师信息出错:', error);
        this.subjectTeachers = [];
        this.classTeacherInfo.headTeacher = '';
      }
    },

    // 根据科目ID获取科目名称
    getSubjectNameById(subjectId) {
      if (subjectId === 0) return '班主任';
      
      const subject = this.schoolSubjectList.find(s => s.id === subjectId);
      return subject ? subject.name : `科目${subjectId}`;
    },

    // 设置任课老师
    async setSubjectTeacher(subjectId) {
      // 显示设置教师对话框
      if (!this.currentNode || !this.currentNode.classId || this.currentNode.classId === 'unassigned') {
        this.$message.warning('请先选择一个班级');          
        return;
      }
      
      // 构建设置信息
      this.settingInfo = {
        class_id: this.currentNode.classId,
        class_name: this.currentNode.label,
        subject_id: subjectId,
        subject_name: this.getSubjectNameById(subjectId),
        teacher_infos: this.subjectTeachers.find(s => s.subjectId === subjectId)?.teachers || []
      };
      
      // 显示设置教师组件
      this.showSetTeacher = true;
    },

    // 设置教师成功的回调
    setTeacherSuccess() {
      this.showSetTeacher = false;
      // 重新获取教师信息
      if (this.currentNode && this.currentNode.classId) {
        console.log('教师设置成功，准备重新获取班级教师信息');
        // 延迟一下，确保后端数据已更新
        setTimeout(() => {
          this.getClassTeacherInfo(this.currentNode.classId);
        }, 300);
      }
      
      // 如果当前是班级列表视图，更新班级列表数据
      if (!this.showStudentView) {
        // 延迟更新，确保后端数据已更新
        setTimeout(() => {
          // 重新获取学校选项数据
          this.GET_SCHOOL_OPTIONS({
            school_id: this.schoolId
          }).then(() => {
            // 更新班级数据
            this.gradeAndClass = JSON.parse(
              JSON.stringify(this.schoolOptions?.F_grades || {})
            );
            // 更新班级列表
            this.updateClassListData();
          });
        }, 500);
      }
    },

    // 更新列设置
    updateColumnList() {
      // 不再更新filterConfig，直接使用checkedList来控制列的显示/隐藏
      console.log('列表设置更新:', this.checkedList);
      
      // 更新列表
      this.getColumnList();
    },

    // 更新班级列表数据
    updateClassListData() {
      // 当点击学校根节点时，显示所有班级
      if (this.currentNode && this.currentNode.id === 'school_root') {
        this.loading = true;
        const allClasses = [];
        
        // 遍历所有年级的班级
        for (const gradeId in this.gradeAndClass) {
          const classes = this.gradeAndClass[gradeId] || [];
          const gradeInfo = this.$maps.gradeList.find(g => g.id === Number(gradeId));
          const gradeName = gradeInfo ? gradeInfo.name : `年级${gradeId}`;
          
          // 添加班级到列表，并附加年级名称前缀
          classes.forEach((classInfo, index) => {
            allClasses.push({
              ...classInfo,
              gradeName: gradeName,
              F_class_name: `${gradeName} - ${classInfo.F_class_name}`,
              F_grade: Number(gradeId),
              headTeacher: classInfo.headTeacher || '未设置',
              teacher_count: classInfo.teacher_count || 0,
              // 确保学生人数有值
              student_count: classInfo.student_count || 0,
              sort: index + 1
            });
          });
        }
        
        // 按年级和班级名称排序
        allClasses.sort((a, b) => {
          if (a.F_grade !== b.F_grade) {
            return a.F_grade - b.F_grade;
          }
          // 提取班级名称中的数字部分进行自然排序
          const aMatch = a.F_class_name.match(/\d+/);
          const bMatch = b.F_class_name.match(/\d+/);
          if (aMatch && bMatch) {
            const aNum = parseInt(aMatch[0], 10);
            const bNum = parseInt(bMatch[0], 10);
            if (aNum !== bNum) {
              return aNum - bNum;
            }
          }
          return a.F_class_name.localeCompare(b.F_class_name);
        });
        
        this.filteredClassList = allClasses;
        this.loading = false;
      } 
      // 当点击年级节点时，仅显示该年级的班级
      else if (this.currentNode && this.currentNode.id.startsWith('grade_')) {
        this.loading = true;
        const gradeId = this.currentNode.gradeId;
        const classes = this.gradeAndClass[gradeId] || [];
        
        // 处理班级列表
        const gradeClasses = classes.map((classInfo, index) => {
          return {
            ...classInfo,
            F_grade: gradeId,
            headTeacher: classInfo.headTeacher || '未设置',
            teacher_count: classInfo.teacher_count || 0,
            // 确保学生人数有值
            student_count: classInfo.student_count || 0,
            sort: index + 1
          };
        });
        
        // 按班级名称排序，考虑数字的自然排序
        gradeClasses.sort((a, b) => {
          // 提取班级名称中的数字部分进行自然排序
          const aMatch = a.F_class_name.match(/\d+/);
          const bMatch = b.F_class_name.match(/\d+/);
          if (aMatch && bMatch) {
            const aNum = parseInt(aMatch[0], 10);
            const bNum = parseInt(bMatch[0], 10);
            if (aNum !== bNum) {
              return aNum - bNum;
            }
          }
          return a.F_class_name.localeCompare(b.F_class_name);
        });
        
        this.filteredClassList = gradeClasses;
        this.loading = false;
      } else {
        this.filteredClassList = [];
      }
    },
    
    // 添加班级
    addClass() {
      // 设置初始化年级ID
      const initGradeId = this.currentNode && this.currentNode.id.startsWith('grade_') ? 
                         this.currentNode.gradeId : 
                         (this.gradeList.length > 0 ? this.gradeList[0].id : 0);
      
      // 打开添加班级对话框
      this.showAddClass = true;
      
      // 通过eventBus触发添加班级事件
      this.$nextTick(() => {
        this.$bus.$emit('init-add-class', {
          gradeId: initGradeId,
          classTotal: this.filteredClassList.length
        });
      });
    },
    
    // 添加班级成功回调
    addNewClass() {
      this.showAddClass = false;
      
      // 重新获取学校选项数据
      this.GET_SCHOOL_OPTIONS({
        school_id: this.schoolId
      }).then(() => {
        // 更新班级数据
        this.gradeAndClass = JSON.parse(
          JSON.stringify(this.schoolOptions?.F_grades || {})
        );
        
        // 重建树形结构
        this.buildTreeData();
        
        // 更新班级列表
        this.updateClassListData();
        
        // 获取真实班级数据
        this.fetchClassDataInfo();
        
        this.$message.success('添加班级成功');  
      });
    },
    
    // 编辑班级
    editClass(classInfo) {
      console.log('编辑班级:', classInfo);
      
      // 设置当前班级信息
      this.currentClassItem = {
        F_id: classInfo.F_class_id,
        F_grade: classInfo.F_grade,
        F_name: classInfo.F_class_name.split(' - ').pop() // 去掉年级前缀
      };
      
      // 打开编辑班级对话框
      this.showEditClass = true;
    },
    
    // 编辑班级成功回调
    updateClass() {
      this.showEditClass = false;
      
      // 重新获取学校选项数据
      this.GET_SCHOOL_OPTIONS({
        school_id: this.schoolId
      }).then(() => {
        // 更新班级数据
        this.gradeAndClass = JSON.parse(
          JSON.stringify(this.schoolOptions?.F_grades || {})
        );
        
        // 重建树形结构
        this.buildTreeData();
        
        // 更新班级列表
        this.updateClassListData();
        
        // 获取真实班级数据
        this.fetchClassDataInfo();
        
        this.$message.success('更新班级成功');
      });
    },
    
    // 删除班级
    deleteClass(index, classInfo) {
      console.log('删除班级:', index, classInfo);
      
      this.$EleMessageBox.confirm(
        `确定要删除班级 "${classInfo.F_class_name}" 吗？`,
        '删除班级',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        this.loading = true;
        try {
          const { F_responseNo, F_responseMsg } = await this.$api.deleteClass({
            F_school_id: this.schoolId,
            F_class_id: classInfo.F_class_id
          });
          
          if (F_responseNo === 10000) {
            this.$message.success('删除班级成功');  
            
            // 重新获取学校选项数据
            await this.GET_SCHOOL_OPTIONS({
              school_id: this.schoolId
            });
            
            // 更新班级数据
            this.gradeAndClass = JSON.parse(
              JSON.stringify(this.schoolOptions?.F_grades || {})
            );
            
            // 重建树形结构
            this.buildTreeData();
            
            // 更新班级列表
            this.updateClassListData();
          } else {
            this.$message.error(`删除班级失败: ${F_responseMsg}`);

          }
        } catch (error) {
          console.error('删除班级出错:', error);
          this.$message.error('删除班级失败，请联系管理员');


        } finally {
          this.loading = false;
        }
      }).catch(() => {
        // 取消删除
      });
    },
    
    // 查看班级学生
    viewClassStudents(classInfo) {
      console.log('查看班级学生:', classInfo);
      
      // 在树结构中找到并点击对应的班级节点
      if (this.$refs.classTree) {
        const nodeKey = `${classInfo.F_grade}_${classInfo.F_class_id}`;
        
        // 遍历树节点找到匹配的班级节点
        const findNode = (data) => {
          for (const node of data) {
            if (node.id === nodeKey) {
              return node;
            }
            if (node.children && node.children.length > 0) {
              const found = findNode(node.children);
              if (found) return found;
            }
          }
          return null;
        };
        
        const targetNode = findNode(this.treeData);
        if (targetNode) {
          this.handleNodeClick(targetNode);
          // 高亮选中节点
          this.$refs.classTree.setCurrentKey(nodeKey);
        } else {
          // 如果在树中没找到节点，手动设置筛选条件
          this.gradeId = classInfo.F_grade;
          this.classId = classInfo.F_class_id;
          this.currentNode = {
            id: nodeKey,
            label: classInfo.F_class_name,
            gradeId: classInfo.F_grade,
            classId: classInfo.F_class_id
          };
          this.page = 1;
          this.getStudents();
          this.getClassTeacherInfo(classInfo.F_class_id);
        }
      }
    },
    // 设置班级教师
    setClassTeachers(classInfo) {
      console.log('设置班级教师:', classInfo);
      
      // 先获取班级的教师信息
      this.getClassTeacherInfo(classInfo.F_class_id);
      
      // 然后打开设置教师对话框
      setTimeout(() => {
        // 构建设置信息
        this.settingInfo = {
          class_id: classInfo.F_class_id,
          class_name: classInfo.F_class_name.split(' - ').pop(), // 去掉年级前缀
          subject_id: 0, // 默认设置班主任
          subject_name: this.getSubjectNameById(0),
          teacher_infos: this.subjectTeachers.find(s => s.subjectId === 0)?.teachers || []
        };
        
        // 显示设置教师组件
        this.showSetTeacher = true;
      }, 800); // 稍微延迟确保教师信息已获取
    },

    // 获取班级的真实数据
    async fetchClassDataInfo() {
      if (!this.schoolId) return;
      
      try {
        const gradeId = this.currentNode && this.currentNode.id.startsWith('grade_') 
                        ? this.currentNode.gradeId : 0;
                        
        const response = await this.$api.getClasses({
          F_school_id: this.schoolId,
          F_grade: gradeId,
          F_page: 1,
          F_limit: 1000
        });
        
        if (response && response.F_classes && response.F_classes.length > 0) {
          // 创建班级ID到详细信息的映射
          const classInfoMap = {};
          
          response.F_classes.forEach(classItem => {
            classInfoMap[classItem.F_id] = {
              student_count: classItem.F_student_num || 0,
              teacher_count: classItem.F_teacher_num || 0,
              headTeacher: classItem.headTeacher || '未设置'
            };
          });
          
          // 更新班级列表中的数据
          this.filteredClassList = this.filteredClassList.map(classInfo => {
            const updatedInfo = classInfoMap[classInfo.F_class_id];
            if (updatedInfo) {
              return {
                ...classInfo,
                student_count: updatedInfo.student_count,
                teacher_count: updatedInfo.teacher_count,
                headTeacher: updatedInfo.headTeacher || classInfo.headTeacher
              };
            }
            return classInfo;
          });
        }
      } catch (error) {
        console.error('获取班级详细信息失败:', error);
      }
    },
    handleClear() {
      // 重置页码
      this.page = 1;
      
      // 如果当前是在学生列表视图且显示的是全校或年级的学生，则切换回班级列表视图
      if (this.showStudentView && (this.currentNode.id === 'school_root' || this.currentNode.id.startsWith('grade_'))) {
        this.showStudentView = false;
        this.updateClassListData();
        this.$nextTick(() => {
          this.fetchClassDataInfo();
        });
      } else {
        // 否则重新获取数据
        this.getStudents();
      }
    }
  },
};
</script>

<style lang="less" scoped>
.student-component {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  padding: 10px;
  
  /* 功能条样式 */
  .function-bar {
    padding: 16px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .left-section {
      display: flex;
      gap: 8px;
      
      .el-button {
        margin-left: 0;
      }
    }
    
    .right-section {
      .search-input {
        width: 260px;
      }
    }
  }
  
  .student-layout {
    display: flex;
    flex: 1;
    min-height: 0; /* 修复Flex布局溢出问题 */
    gap: 16px;
    
    /* 左侧班级树形结构 */
    .class-tree-container {
      width: 280px;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      display: flex;
      flex-direction: column;
      min-height: 400px; /* 确保容器有最小高度 */
      
      .tree-header {
        padding: 15px;
        font-size: 16px;
        font-weight: bold;
        color: #409EFF;
        border-bottom: 1px solid #e6e6e6;
        display: flex;
        justify-content: space-between;
        
        i {
          margin-right: 5px;
        }
        
        .debug-toggle {
          cursor: pointer;
          font-size: 14px;
          color: #909399;
          
          &:hover {
            color: #F56C6C;
          }
        }
      }
      
      .el-tree {
        flex: 1;
        overflow: auto;
        padding: 10px;
        
        .custom-tree-node {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: space-between;
          font-size: 14px;
          padding-right: 8px;
          
          .count-tag {
            margin-left: 5px;
            color: #909399;
            font-size: 12px;
          }
        }
        
        .node-selected {
          color: #409EFF;
          font-weight: bold;
        }
      }
      
      .empty-tree, .loading-tree {
        padding: 20px;
        text-align: center;
        color: #909399;
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        
        i {
          font-size: 42px;
          margin-bottom: 10px;
        }
        
        p {
          margin: 0;
          font-size: 14px;
        }
      }
      
      .loading-tree {
        color: #409EFF;
        
        i {
          animation: rotating 2s linear infinite;
        }
        
        @keyframes rotating {
          from {
            transform: rotate(0deg);
          }
          to {
            transform: rotate(360deg);
          }
        }
      }
    }
    
    /* 右侧内容区 */
    .student-list-container {
      flex: 1;
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      display: flex;
      flex-direction: column;
      min-width: 0; /* 防止内容溢出 */
      min-height: 400px; /* 确保容器有最小高度 */
      
      .class-info-header {
        padding: 16px 20px;
        border-bottom: 1px solid #e6e6e6;
        background-color: #fff;
        flex-shrink: 0;
        
        .header-row {
          display: flex;
          align-items: center;
          
          .class-title {
            display: flex;
            flex-direction: column;
            gap: 4px;
            
            h2 {
              font-size: 18px;
              font-weight: 600;
              color: #303133;
              margin: 0;
              line-height: 1.2;
            }
            
            .subtitle {
              font-size: 14px;
              color: #909399;
              font-weight: normal;
            }
          }
        }
      }
      
      .scrollable-content {
        flex: 1;
        overflow: auto;
        padding: 0 20px;
        position: relative; /* 确保loading状态定位正确 */
        min-height: 300px; /* 确保内容区有最小高度 */
        
        .class-list-section {
          padding: 20px 0;
          display: flex;
          flex-direction: column;
          flex: 1;
          min-height: 0;
          
          .action-buttons {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            margin-bottom: 16px;
            gap: 8px;
            
            .el-button {
              margin: 0;
              padding: 8px 16px;
              font-size: 13px;
            }
          }
          
          .table-wrapper {
            flex: 1;
            display: flex;
            flex-direction: column;
            min-height: 200px;
            overflow: hidden;
            
            :deep(.el-table) {
              flex: 1;
              
              .table-header {
                background-color: #f5f7fa;
                color: #606266;
                font-weight: 600;
              }
              
              &__body-wrapper {
                overflow-y: auto;
                
                &::-webkit-scrollbar {
                  width: 8px;
                }
                
                &::-webkit-scrollbar-thumb {
                  background-color: rgba(144, 147, 153, 0.3);
                  border-radius: 4px;
                  
                  &:hover {
                    background-color: rgba(144, 147, 153, 0.5);
                  }
                }
                
                &::-webkit-scrollbar-track {
                  background-color: transparent;
                }
              }
              
              &__row {
                transition: background-color 0.2s;
                
                &:hover {
                  background-color: #f5f7fa;
                }
                
                td {
                  padding: 12px 0;
                  border-bottom: 1px solid #ebeef5;
                }
              }
              
              &__header th {
                padding: 12px 0;
                font-weight: 600;
                background-color: #f5f7fa;
              }
              
              .count-text {
                font-weight: 500;
                color: #606266;
              }
              
              .action-buttons-cell {
                display: flex;
                justify-content: center;
                align-items: center;
                gap: 8px;
                
                .view-btn {
                  color: #409EFF;
                  
                  &:hover {
                    color: #66b1ff;
                  }
                }
                
                .edit-btn {
                  color: #409EFF;
                  
                  &:hover {
                    color: #66b1ff;
                  }
                }
                
                .delete-btn {
                  color: #f56c6c;
                  
                  &:hover {
                    color: #f78989;
                  }
                }
              }
            }
          }
        }
        
        .student-section {
          margin-top: 16px;
          
          .section-header {
            margin-bottom: 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            
            .section-title {
              display: flex;
              align-items: center;
              font-size: 16px;
              font-weight: bold;
              
              i {
                margin-right: 8px;
              }
            }
            
            .action-buttons {
              display: flex;
              gap: 8px;
            }
          }
        }
        
        .teacher-section-header {
          margin: 16px 0;
          padding-bottom: 10px;
          border-bottom: 1px dashed #ebeef5;
        }
        
        .teacher-info {
          .teacher-info-row {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            
            .teacher-item {
              padding: 8px 12px;
              border: 1px solid #ebeef5;
              border-radius: 4px;
              display: flex;
              align-items: center;
              
              .label {
                color: #606266;
                margin-right: 8px;
              }
              
              .value {
                color: #409EFF;
                cursor: pointer;
              }
            }
          }
        }
        
        .table-wrapper {
          margin: 16px 0;
        }
      }
      
      .footer {
        padding: 16px 0;
        display: flex;
        justify-content: center;
        border-top: 1px solid #ebeef5;
      }
    }
  }
}

/* 自定义滚动条样式 */
.scrollable-content::-webkit-scrollbar,
.el-tree::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.scrollable-content::-webkit-scrollbar-thumb,
.el-tree::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background: #c0c4cc;
}

.scrollable-content::-webkit-scrollbar-track,
.el-tree::-webkit-scrollbar-track {
  border-radius: 3px;
  background: #f5f7fa;
}

/* Element UI 组件样式覆盖 */
:deep(.el-tree-node__content) {
  height: 40px;
}

:deep(.el-tree-node:focus > .el-tree-node__content) {
  background-color: #f0f7ff;
}

:deep(.el-tree-node__expand-icon) {
  padding: 8px;
}

:deep(.el-tree-node__label) {
  font-size: 14px;
}

:deep(.el-table) {
  border: none;
  
  th {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 500;
  }
}

:deep(.el-pagination) {
  padding: 10px 0;
}

:deep(.el-button--text) {
  padding: 0 5px;
}
</style>

<style lang="less">
.column-setting-popover-content {
  .el-checkbox-group {
    .el-checkbox {
      display: block;
      line-height: 30px;
      .el-checkbox__label {
        font-size: 16px;
      }
    }
  }
}

/* 覆盖全局样式 */
.el-table th.is-leaf {
  background-color: #f5f7fa;
}

.el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fcfcfc;
}
</style>

.loading-tree {
  padding: 20px;
  text-align: center;
  color: #909399;
  
  i {
    font-size: 42px;
    margin-bottom: 10px;
  }
  
  p {
    margin: 0;
    font-size: 14px;
  }
}